package blue.http.internal.core.plugin;

import blue.base.core.util.AssertUtil;
import blue.http.core.message.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author Jin Zheng
 * @since 1.0 2021-08-26
 */
public class MemorySession implements Session {
	private static Logger logger = LoggerFactory.getLogger(MemorySession.class);

	private String token;
	private String key;
	private final MemorySessionProvider provider;
	private final ConcurrentMap<String, Object> attrMap = new ConcurrentHashMap<>();

	public MemorySession(String token, MemorySessionProvider provider) {
		AssertUtil.notEmpty(token, "Token");
		this.token = token;
		this.provider = provider;
	}

	@Override
	public String getToken() {
		return token;
	}

	@Override
	public void setKey(String key) {
		this.key = key;
		provider.setKey(token, key);
	}

	@Override
	public String getKey() {
		return key;
	}

	@Override
	public void delete() {
		provider.removeSession(token);
	}

	@Override
	public Map<String, Object> getAttrs() {
		return Map.copyOf(attrMap);
	}

	@Override
	public Object getAttr(String key) {
		return attrMap.get(key);
	}

	@Override
	public void setAttr(String key, Object value) {
		attrMap.put(key, value);
	}

	@Override
	public void removeAttr(String key) {
		attrMap.remove(key);
	}

	@Override
	public void clearAttr() {
		attrMap.clear();
	}
}
